package com.gitee.fastmybatis.core.proxy;

import com.gitee.fastmybatis.core.MybatisContext;
import org.apache.ibatis.session.SqlSessionFactory;

import java.lang.reflect.Proxy;

/**
 * @author 六如
 */
public class MapperProxyFactory<T> {
    private final Class<T> mapperInterface;

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public T newInstance() {
        SqlSessionFactory sqlSessionFactory = MybatisContext.getSqlSessionFactoryByMapperClass(mapperInterface);
        if (sqlSessionFactory == null) {
            throw new IllegalArgumentException("SqlSessionFactory not found by mapper class:" + mapperInterface);
        }
        final MapperProxy mapperProxy = new MapperProxy(mapperInterface, sqlSessionFactory);
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }
}
